﻿Imports System.Data.SqlClient

Public Class <Database>DataService
    Implements I<Database>DataService

    Public Shared connectionString As String _
            = "<ConnectionString>"

    Public Shared Function GetConnection() As SqlConnection
        Dim connection As New SqlConnection(connectionString)
        Return connection
    End Function

    Public Function getIdent_Current(ByVal Table As String) As Integer Implements I<Database>DataService.getIdent_Current
        Dim query As String
        Dim connection As New SqlConnection
        Dim command As New SqlCommand
        Dim reader As SqlDataReader
        Dim returnValue As Integer = 0

        query = "SELECT IDENT_CURRENT('" & Table & "')"
        connection = GetConnection()
        command = New SqlCommand(query, connection)
        command.CommandType = CommandType.Text
        Try
            connection.Open()
            reader = command.ExecuteReader()
            If reader.HasRows = True Then
                While reader.Read()
                    returnValue = System.Convert.ToInt32(reader.GetValue(0))
                End While
            End If
            reader.Close()
            connection.Close()
        Catch ex As SqlException
            MsgBox(ex.Message, CType(ex.GetType.ToString, MsgBoxStyle))
        Finally
            connection.Close()
        End Try
        Return returnValue
    End Function

    Public Function getIdent_Incr(ByVal Table As String) As Integer Implements I<Database>DataService.getIdent_Incr
        Dim query As String
        Dim connection As New SqlConnection
        Dim command As New SqlCommand
        Dim reader As SqlDataReader
        Dim returnValue As Integer = 0

        query = "SELECT IDENT_INCR('" & Table & "')"
        connection = GetConnection()
        command = New SqlCommand(query, connection)
        command.CommandType = CommandType.Text
        Try
            connection.Open()
            reader = command.ExecuteReader()
            If reader.HasRows = True Then
                While reader.Read()
                    returnValue = System.Convert.ToInt32(reader.GetValue(0))
                End While
            End If
            reader.Close()
            connection.Close()
        Catch ex As SqlException
            MsgBox(ex.Message, CType(ex.GetType.ToString, MsgBoxStyle))
        Finally
            connection.Close()
        End Try
        Return returnValue
    End Function

    Public Function getAutoID(ByVal Mode As String, ByVal Table As String) As Integer Implements I<Database>DataService.getAutoID
        Dim Ident_Current As Integer = getIdent_Current(Table)
        If Mode = "Last" Then
            Return Ident_Current
        ElseIf Mode = "New" Then
            Return Ident_Current + getIdent_Incr(Table)
        End If
        Return Nothing
    End Function

End Class
 
